package com.sky.wsp.license.utils;

import org.bouncycastle.util.encoders.Base64;

import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.*;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 证书工具类（主要用于获取公钥）
 * @date 2024/6/24
 */
public class CertificateUtil {
    public static X509Certificate getCertificate(KeyStore keyStore, String alias) {
        try {
            X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
            return certificate;
        } catch (KeyStoreException e) {
            throw new RuntimeException(e);
        }
    }
    public static String certificateToStr(X509Certificate certificate) {
        try {
            byte[] encodedCert = certificate.getEncoded();
            String base64Cert = Base64.toBase64String(encodedCert);
            return base64Cert;
        } catch (CertificateEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static X509Certificate strToCertificate(String str){
        byte[] decodeCert = Base64.decode(str);
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(decodeCert));
            return certificate;
        } catch (CertificateException e) {
            throw new RuntimeException(e);
        }
    }
}
